package identx

import (
	"math/rand"
	"sync"
	"sync/atomic"
	"time"
)

func init() {
	identInt = NewIdentInt()
	identInt.resetObjectIDCounter()

	//SetNode(3844 + rander.Intn(238328-3844))
}

var identInt *IdentInt

func GenTimeCount() int64 {
	return identInt.GenOne()
}

func NewIdentInt() (obj *IdentInt) {
	obj = &IdentInt{}
	obj.rander = rand.New(rand.NewSource(time.Now().UnixNano()))
	return
}

type IdentInt struct {
	rander          *rand.Rand
	objectIDCounter uint32
	mutex           sync.Mutex

	lastTimestamp int64
}

func (ii *IdentInt) GenOne() int64 {
	ii.mutex.Lock()
	defer ii.mutex.Unlock()
	now := timeGen()
	if now > ii.lastTimestamp {
		ii.lastTimestamp = now
		ii.resetObjectIDCounter()
	}
	count := uint64(atomic.AddUint32(&ii.objectIDCounter, 1))
	countInt64 := int64(count << 32)
	ident := countInt64 + ii.lastTimestamp
	return ident
}
func (ii *IdentInt) resetObjectIDCounter() {
	//ii.objectIDCounter = 0
	ii.objectIDCounter = uint32(3844 + ii.rander.Intn(65535-3844))
}
